# -*- coding: utf-8 -*-
import json,os
from jinja2 import Markup
from flask import flash, url_for, redirect, request, current_app
from flask_admin.base import expose
from flask_admin.model.template import EndpointLinkRowAction, LinkRowAction
from flask_wtf import FlaskForm
from sqlalchemy import func
from wtforms import SelectMultipleField, ValidationError
from wtforms.validators import DataRequired
from flask_admin.actions import action
from flask_admin.helpers import (get_form_data, validate_form_on_submit,get_redirect_target, flash_errors)
from flask_admin.contrib.sqla import form, filters as sqla_filters, tools
from . import MyModelView
from . import AjaxQueryIndexLike
from adminApp.extensions import db, redis_store


class IdcView(MyModelView):
    column_filters = ('name', 'mark', 'address', 'remark', 'created')

    column_list = ('id', 'name', 'mark', 'machines_count', 'address', 'remark', 'created')
    # column_sortable_list = (
    #     'id', 'name', 'category.name', 'author.name', 'serial_state', 'words', 'last_updated', 'created')

    column_labels = {
        'machines_count':'设备数量',
        'name': '机房名称',
        'mark': '分段标识',
        'address': '地址',
        'remark': '备注',
        'created': '创建日期',
        'updated': '更新日期',
    }

    column_formatters = dict(
        machines_count=lambda v, c, m, p: m.machines.count(),
        created=lambda v, c, m, p: m.created.strftime("%Y-%m-%d %H:%M:%S"),
        updated=lambda v, c, m, p: m.updated.strftime("%Y-%m-%d %H:%M:%S") if m.updated else ''
    )
    form_columns = ('name', 'mark', 'address', 'remark')

    create_modal = True
    edit_modal = True
    details_modal = True

    def on_model_delete(self, model):
        if model.machines.count()>0:
            raise ValidationError('还有下属设备记录，不能删除！请先删除下属设备记录！')